﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace Quickuse.Logging.HttpLogger
{
    /// <summary>
    /// HttpLoggerProvider
    /// </summary>
    internal sealed class HttpLoggerProvider : LoggerProvider
    {
        private readonly ConcurrentDictionary<string, HttpLogger> _loggers = new ConcurrentDictionary<string, HttpLogger>();

        private IHttpLoggerSettings _httpLoggerSettings;
        private IExternalScopeProvider scopeProvider;

        /// <summary>
        /// HttpLoggerProvider
        /// </summary>
        /// <param name="httpLoggerSettings">httpLoggerSettings</param>
        /// <param name="httpLoggerProcessor">httpLoggerProcessor</param>
        /// <param name="filter">filter</param>
        public HttpLoggerProvider(IHttpLoggerSettings httpLoggerSettings, HttpLoggerProcessor httpLoggerProcessor, Func<string, LogLevel, bool> filter = null)
            : base(httpLoggerProcessor.EnqueueMessage, filter)
        {
            if (httpLoggerSettings == null)
            {
                throw new ArgumentNullException(nameof(httpLoggerSettings));
            }
            _httpLoggerSettings = httpLoggerSettings;

        }

        /// <summary>
        /// GetScopeProvider
        /// </summary>
        /// <returns></returns>
        private IExternalScopeProvider GetScopeProvider()
        {
            if (_httpLoggerSettings.IncludeScopes && scopeProvider == null)
            {
                scopeProvider = new LoggerExternalScopeProvider();
            }
            return _httpLoggerSettings.IncludeScopes ? scopeProvider : null;
        }

        /// <summary>
        /// CreateLogger
        /// </summary>
        /// <param name="categoryName">categoryName</param>
        /// <returns></returns>
        public override ILogger CreateLogger(string categoryName)
        {
            return _loggers.GetOrAdd(categoryName, (categoryName1) =>
            {
                return new HttpLogger(categoryName1, _httpLoggerSettings, LogCallback, Filter, GetScopeProvider());
            });
        }

        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
            //throw new NotImplementedException();
        }
    }
}
